package com.hkemmm.converter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTypeConverter implements Converter<String, Date> {
    private static final String STR_DATE = "yyyy-MM-dd";
    private static final String STR_DATETIME = "yyyy-MM-dd HH:mm:ss";
    private static final String STR_TIMESTAMP = "yyyy-MM-dd HH:mm:ss.SSSS";


    @Override
    public Date convert(String s) {
        return toDate(s);
    }

    private Date toDate(String value) {
        Date date = null;

        if (StringUtils.isNotEmpty(value)) {
            //剔除空格
            String strDateValue = value.trim();
            String strFormat = STR_DATE;

            if (strDateValue.length() <= 10) {

            } else if (strDateValue.length() <= 19) {
                strFormat = STR_DATETIME;
            } else if (strDateValue.length() <= 23) {
                strFormat = STR_TIMESTAMP;
            }


            try {
                SimpleDateFormat sdf = new SimpleDateFormat(strFormat);
                strDateValue = strDateValue.replace("/","-");
                date = sdf.parse(strDateValue);
            } catch (ParseException e) {
                System.out.println("数据类型转化错误:" + e.getMessage());
            }
        }

        return date;
    }
//     //测试数据
//    public static void main(String[] args) {
//        String s = "1998-06-20 24:15:2";
//
//        Date date = toDate(s);
//        System.out.println(date);
//    }
}
